package com.gp.learn.ssm.base.system.service.impl;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.gp.learn.ssm.base.core.mybaits.base.service.impl.BaseServiceImpl;
import com.gp.learn.ssm.base.core.security.SecurityConstants;
import com.gp.learn.ssm.base.core.security.model.OpenAuthority;
import com.gp.learn.ssm.base.core.security.model.UserInfo;
import com.gp.learn.ssm.base.system.entity.BaseRole;
import com.gp.learn.ssm.base.system.entity.BaseUser;
import com.gp.learn.ssm.base.system.mapper.BaseUserMapper;
import com.gp.learn.ssm.base.system.service.BaseAuthorityService;
import com.gp.learn.ssm.base.system.service.BaseRoleUserService;
import com.gp.learn.ssm.base.system.service.BaseUserService;
import com.gp.learn.ssm.common.constants.CommonConstants;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;

/**
 * 系统用户-基础信息 服务实现类
 *
 * @author gp
 * @since 2020-07-24
 */
@Service
public class BaseUserServiceImpl extends BaseServiceImpl<BaseUserMapper, BaseUser> implements BaseUserService {
    @Autowired
    private BaseRoleUserService baseRoleUserService;
    @Autowired
    private BaseAuthorityService baseAuthorityService;

    @Override
    public UserInfo getUserWithAuthoritiesById(Long userId) {
        List<Map> roles = Lists.newArrayList();
        List<OpenAuthority> authorities = Lists.newArrayList();
        //查询用户角色
        List<BaseRole> baseRoleList = baseRoleUserService.selectRoleListByUser(userId);
        for (BaseRole baseRole : baseRoleList) {
            Map map = Maps.newHashMap();
            Long roleId = baseRole.getRoleId();
            String roleCode = baseRole.getRoleCode();
            String roleName = baseRole.getRoleName();
            map.put("roleId", roleId);
            map.put("roleCode", roleCode);
            map.put("roleName", roleName);
            roles.add(map);
            // 加入角色标识
            OpenAuthority authority = new OpenAuthority(roleId.toString(), SecurityConstants.AUTHORITY_PREFIX_ROLE + roleCode, null, "role");
            authorities.add(authority);
        }
        //查询用户资源
        BaseUser baseUser = getById(userId);
        UserInfo userInfo = new UserInfo();
        BeanUtils.copyProperties(baseUser, userInfo);
        // 加入用户权限
        List<OpenAuthority> userGrantedAuthority = baseAuthorityService.findAuthorityByUser(userId, CommonConstants.ROOT.equals(userInfo.getUserName()));
        if (userGrantedAuthority != null && userGrantedAuthority.size() > 0) {
            authorities.addAll(userGrantedAuthority);
        }
        userInfo.setRoles(roles);
        userInfo.setAuthorities(authorities);
        return userInfo;
    }
}
